
// const axios = require('axios');
// const apiKey = ''; // 替换为你的 OpenAI API 密钥
// // 创建 Axios 实例反向代理梯子，不然翻不过去
// const axiosInstance = axios.create({
//     proxy: {
//         host: '127.0.0.1',
//         port: 7890,
//         protocol: 'http' // 指定代理服务器的协议
//     },
//     headers: {
//         Authorization: "Bearer " + apiKey,
//     },
// });

// // 发送请求到自己的服务器，会经过反向代理
// axiosInstance.post('https://api.xty.app/v1', {
//     // 请求数据
//     model: "gpt-3.5-turbo",
//     messages: [
//         {
//             "role": "user",
//             "content": "为什么我还没调用接口，请求都已经超出了限制\n"
//         },
//     ],

// })
//     .then(response => {
//         console.log(response.data);
//     })
//     .catch(error => {
//         console.error('Error:', error);
//     });

const OpenAI = require('openai');
const WebSocket = require('ws');
const net = require('net');

const openai = new OpenAI({
    apiKey: '写你自己的sdk密钥', //换成自己的sdk
    baseURL: "https://hk.xty.app/v1" // 去掉多余的空格
});

// 根据message内容调用openai接口
const callOpenAIDialogAPI = async (message) => {
    const completion = await openai.chat.completions.create({
        model: "gpt-3.5-turbo",
        messages: [{ role: "system", content: message }],
    });
    console.log(completion.choices[0]);
    return completion.choices[0].message.content;
}

// 返回一个 Promise，以便在 WebSocket 服务器构建完成后解析并返回状态
exports.callDialogAPI = async () => {
    return new Promise((resolve, reject) => {
        const server = net.createServer();

        server.on('listening', () => {
            const port = server.address().port;
            server.close(() => {
                const wss = new WebSocket.Server({ host: '0.0.0.0', port: port });

                const clients = new Map();

                wss.on('connection', function connection(ws) {
                    console.log('Client connected');
                    clients.set(ws, true);
                    ws.send('AI会话已经为您配置完毕,快和我对话吧!')
                    ws.on('message', async function incoming(message) {
                        const msg = await callOpenAIDialogAPI(message.toString('utf8'))
                        ws.send(msg)
                    });

                    ws.on('close', function () {
                        console.log('Client disconnected');
                        clients.delete(ws);
                    });
                });

                wss.on('listening', () => {
                    console.log('WebSocket server is ready');
                    resolve({
                        status: 0,
                        url: `ws://localhost:${port}`
                    });
                });

                wss.on('error', (error) => {
                    reject(error);
                });
            });
        });

        server.on('error', (error) => {
            reject(error);
        });

        server.listen(0, '0.0.0.0');
    });
}